package com.pansoft.mobilemallpay;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.ospopenplanet.wxapi.WXPayEntryActivity;
import com.efounder.utils.ResStringUtil;
import com.pansoft.mobilemallpay.bean.OrderBean;
import com.pansoft.mobilemallpay.pays.AliPay;
import com.pansoft.mobilemallpay.pays.OnPayListener;
import com.pansoft.mobilemallpay.pays.PayInter;
import com.pansoft.mobilemallpay.pays.WxPay;
import com.utilcode.util.ActivityUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

public class PayOrderActivity extends AppCompatActivity implements View.OnClickListener {


    private ImageView backButtonTitleMyLive;
    private TextView textTitleMyLive;
    private TextView googName;
    private TextView description;
    private TextView orderMoney;
    private ImageView alicheckImage;
    private LinearLayout alicheckBtn;
    private ImageView wxcheckImage;
    private LinearLayout wxcheckBtn;
    private Button orderPayBtn;
    private LinearLayout activityPayOrder;
    private String payType = "ali";
    private OrderBean mOrderBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_order);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mOrderBean = bundle.getParcelable("orderBean");
            initFindView();
        }
    }

    private void initFindView() {
        backButtonTitleMyLive = (ImageView) findViewById(R.id.backButton_title_my_live);
        textTitleMyLive = (TextView) findViewById(R.id.text_title_my_live);
        googName = (TextView) findViewById(R.id.googName);

        description = (TextView) findViewById(R.id.description);
        orderMoney = (TextView) findViewById(R.id.orderMoney);
        alicheckImage = (ImageView) findViewById(R.id.alicheckImage);

        alicheckBtn = (LinearLayout) findViewById(R.id.alicheckBtn);
        wxcheckImage = (ImageView) findViewById(R.id.wxcheckImage);
        wxcheckBtn = (LinearLayout) findViewById(R.id.wxcheckBtn);
        orderPayBtn = (Button) findViewById(R.id.orderPayBtn);
        activityPayOrder = (LinearLayout) findViewById(R.id.activity_pay_order);
        findViewById(R.id.bar).setBackgroundColor(getResources().getColor(R.color.chat_red));

        orderPayBtn.setOnClickListener(this);
        alicheckBtn.setOnClickListener(this);
        wxcheckBtn.setOnClickListener(this);

        orderMoney.setText(ResStringUtil.getString(R.string.mobile_mall_pay_unit) + mOrderBean.getTotalamount());
        googName.setText(mOrderBean.getGoodName());
        description.setText(mOrderBean.getTitle());
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.orderPayBtn) {
            //去支付;
            pay(payType);
        } else if (id == R.id.wxcheckBtn) {
            alicheckImage.setImageResource(R.drawable.shape_circle_dot);
            wxcheckImage.setImageResource(R.drawable.check_selected);
            payType = "wx";
        } else if (id == R.id.alicheckBtn) {
            wxcheckImage.setImageResource(R.drawable.shape_circle_dot);
            alicheckImage.setImageResource(R.drawable.check_selected);
            payType = "ali";
        }
    }


    private void pay(String type) {
        if (mOrderBean == null) {
            showToast(ResStringUtil.getString(R.string.mobile_mall_pay_request_order_empty));
            return;
        }
        HashMap<String, String> orderBeanMap = mOrderBean.getOrderBeanMap();
        //请求订单号
        PayInter pay = null;
        if ("wx".equals(type)) {
            //wx支付
            pay = new WxPay(this);
        } else {
            pay = new AliPay(this);
        }
        orderBeanMap.put("paytype", payType);
        //监听页面
        listenerActivityNotifycation();

        String url = EnvironmentVariable.getProperty("videoURL") + "/PayService";
        pay.setURLAndParams(url, orderBeanMap);

        //无法直接向wxpayentryactivity传值,如果支付方式是微信的话,醉了醉了;
        EnvironmentVariable.setProperty("mobile_pay_good_name", mOrderBean.getGoodName());
        EnvironmentVariable.setProperty("mobile_pay_good_description", mOrderBean.getTitle());
        EnvironmentVariable.setProperty("mobile_pay_good_price", mOrderBean.getTotalamount());
        final PayInter finalPay = pay;
        pay.pay(new OnPayListener() {
            @Override
            public void onPaySuccess() {
                showToast(ResStringUtil.getString(R.string.mobile_mall_pay_success));
                if (finalPay instanceof AliPay) {
                    //阿里支付成功后需要手动跳转到支付成功界面
                    //微信会自动跳转到成功界面;
                    Intent intent = new Intent(PayOrderActivity.this, WXPayEntryActivity.class);
                    intent.putExtra("type", "ali");
                    intent.putExtra("status", "success");
                    startActivity(intent);
                }
            }

            @Override
            public void onPayFailure(String msg, int code) {
                if (code == OnPayListener.ERROR) {
                    showToast(ResStringUtil.getString(R.string.mobile_mall_pay_request_prepayment_failed));
                    if (finalPay instanceof AliPay) {
                        //阿里支付成功后需要手动跳转到支付成功界面
                        //微信会自动跳转到成功界面;
                        Intent intent = new Intent(PayOrderActivity.this, WXPayEntryActivity.class);
                        intent.putExtra("type", "ali");
                        intent.putExtra("status", "failure");
                        startActivity(intent);
                    }
                }
            }
        });
    }

    private void listenerActivityNotifycation() {
        LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LocalBroadcastManager.getInstance(PayOrderActivity.this).unregisterReceiver(this);
                finish();
            }
        }, new IntentFilter(WXPayEntryActivity.FINISH_ORDER_ACTIVITY));
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    public static void open(String good_name, String goodId, float price, String title) {

        String subject = good_name;
        try {
            subject = URLEncoder.encode(subject, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            subject = "app";

        }
        OrderBean orderBean = new OrderBean();
        orderBean.setUserid(EnvironmentVariable.getUserID())
                .setTotalamount(String.valueOf(price))
                .setBody(good_name)
                .setSubject(subject)
                .setGoodName(good_name)
                .setTitle(title)
                .setGoodid(goodId);
        Bundle bundle = new Bundle();
        bundle.putParcelable("orderBean", orderBean);
        ActivityUtils.startActivity(bundle, PayOrderActivity.class);
    }


}
